import json

from workflow.models import Task, WorkflowApprovalNode, Admin
from workflow.serial import TaskSerializer, AuditRecordSerializer
from langchain_community.llms import Tongyi
from langchain_core.prompts import PromptTemplate
from langchain.agents import create_react_agent, AgentExecutor, Tool
from mycelery.all_task.task import send_email_to


# 添加任务
def add_task(input):
    the_message = json.loads(input)
    print("the_message:", the_message)
    task_data = the_message.get("message")
    serializer = TaskSerializer(data=task_data)
    if serializer.is_valid():
        serializer.save()
        print("返回数据id：", serializer.data["id"])
        return serializer.data["id"]
    else:
        return serializer.errors

# 获取下一审核人
def get_next_reviewer(input):
    the_message = json.loads(input)
    print("the_message:", the_message)
    # task_id = the_message.get("message")
    task_id = int(the_message.get("message"))
    print("task_id:", task_id)
    task = Task.objects.get(id=task_id)
    if task.task_status == 3:
        return "审批结束，未通过审批。"
    # 获取当前工作流和当前执行步骤
    workflow = task.workflow
    level = task.level
    # 获取下一步工作流审批模型对象
    try:
        approval_node = WorkflowApprovalNode.objects.get(workflow=workflow, level=(level + 1))
    except WorkflowApprovalNode.DoesNotExist:
        task.task_status = 2
        task.next_audit = None
        task.save()
        return "审批结束，通过审批。"

    # 获取用户
    admin_id = task.admin_id
    admin = Admin.objects.get(id=admin_id)
    # 获取当前部门
    department = admin.department
    # 获取审核人职位
    position = approval_node.position
    # 获取审核人
    admin = Admin.objects.get(department=department, position=position)

    # 修改任务表
    task.level = level + 1
    task.next_audit = admin
    task.save()
    return "下一审核人：" + admin.name

# 填写审批记录
def add_audit_record(input):
    the_message = json.loads(input)
    print("审批的the_message:", the_message)
    data = the_message.get("message")
    # 如果不通过，则申请驳回，并修改任务表
    if not data.get("audit_status"):
        task = Task.objects.get(id=data.get("task_id"))
        task.task_status = 3
        task.next_audit = None
        task.save()
    # 发送邮件
    if data.get("audit_status"):
        result = "审批通过"
    else:
        result = "审批未通过"
    message = result + "，审批意见：" + data.get("note")
    print("审批结果：", message)
    # send_email_to.delay("derek59117@163.com", message)

    # subject = "审批结果"
    # print(settings.EMAIL_FROM)
    # from_email = settings.EMAIL_FROM
    # to_email = ["derek59117@163.com"]
    # send_status = send_mail(subject, message, from_email, to_email)
    # print(send_status)

    # 填写审批表
    serializer = AuditRecordSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return "审批记录填写成功。"
    else:
        return serializer.errors


def audit_workflow(message):
    print("原生message:", message)
    tools = [
        Tool(func=add_task, name="add_task", description="添加任务"),
        Tool(func=get_next_reviewer, name="get_next_reviewer", description="获取下一审核人"),
        Tool(func=add_audit_record, name="add_audit_record", description="填写审批记录")
    ]
    template = '''Answer the following questions as best you can. You have access to the following tools,

                {tools}

                Use the following format:

                Question: the input question you must answer,传递参数时不要自己处理，只传递input参数即可，不要进行修改，不要删除title字段
                Thought: you should always think about what to do
                Action: the action to take, should be one of [{tool_names}]
                Action Input: the input to the action
                Observation: the result of the action
                ... (this Thought/Action/Action Input/Observation can repeat N times)
                Thought: I now know the final answer
                Final Answer: the final answer to the original input question,请不要添加自己的回答,只返回工具返回内容即可,不要添加自己的文字:
                                
                Begin!

                Question: {input}
                Thought:{agent_scratchpad}'''

    prompt = PromptTemplate.from_template(template)

    llm = Tongyi()
    agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    response = agent_executor.invoke({"input": message})
    print(response)
    return response
    # add_task_return_data = response.get("Observation")
    # print("add_task_return_data:", add_task_return_data)
